package com.goddess.yeecolor.fragment.ExerciseitemFragment;

import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.goddess.yeecolor.Modle.Comment;
import com.goddess.yeecolor.Modle.basic;
import com.goddess.yeecolor.Modle.belong_info;
import com.goddess.yeecolor.Modle.comments;
import com.goddess.yeecolor.Modle.user_info;
import com.goddess.yeecolor.R;
import com.goddess.yeecolor.activity.CommitActivity;
import com.goddess.yeecolor.activity.LoginAcitivity;
import com.goddess.yeecolor.adapter.Item_Exerciseitem_commitAdapter2;
import com.goddess.yeecolor.adapter.item_Exerciseitem_commit_contentAdapter;
import com.goddess.yeecolor.base.BaseFragment;
import com.goddess.yeecolor.interfaceAll.OnClickListener;
import com.goddess.yeecolor.tools.JumpIntents;
import com.goddess.yeecolor.tools.LogUtils;
import com.goddess.yeecolor.tools.MyUrl;
import com.goddess.yeecolor.tools.OkttpUtils;
import com.goddess.yeecolor.tools.SharePreceUtils;
import com.goddess.yeecolor.tools.ToastUtils;
import com.goddess.yeecolor.view.RecycleViewDivider;
import com.goddess.yeecolor.view.dialog_progress;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;



/**
 * 活动评论
 */
public class ExerciseItem_activityCommit extends BaseFragment {
    private JSONArray array;
    private View mView;
    private String id;
    private Bundle mBundle;
    private boolean isLogin=false;
    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (mView==null){
            mView=inflater.inflate(R.layout.fragment_activitycommit,container,false);
            initFindView();
            initOnClck();
        }
        return mView;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mBundle=getArguments();
        if (mBundle!=null){
            id=mBundle.getString("id");
        }
    }

    public static ExerciseItem_activityCommit newInstance(String id) {
        ExerciseItem_activityCommit newFragment = new ExerciseItem_activityCommit();
        Bundle bundle = new Bundle();
        bundle.putString("id",id);
        newFragment.setArguments(bundle);
        return newFragment;
    }
    @Override
    public void initOnClck() {
        exerciseitem_commit.setOnClickListener(addCommentListener);
    }

    @Override
    public void initFindView() {
        init();
    }

    @Override
    public void initData() {


    }


    private RecyclerView lv_user_comments;
    private static final int ONE_COMMENT_CODE = -1;
    private item_Exerciseitem_commit_contentAdapter commentReplyAdapter;
    private List<Comment> commentList= new ArrayList<Comment>();

    private RecyclerView exerciseitem_commit_contents;
    private LinearLayoutManager manager;
    private XRefreshView xRefreshView;
    public static long lastRefreshTime;
    private TextView exerciseitem_commit;
    private LinearLayoutManager mLinearManager;
    private Item_Exerciseitem_commitAdapter2 commentAdapter;
    private String more="0";
    private void init() {
        exerciseitem_commit = (TextView) mView.findViewById(R.id.exerciseitem_commit);
//        xRefreshView = (XRefreshView) mView.findViewById(R.id.commit_xrefresh);
        lv_user_comments = (RecyclerView) mView.findViewById(R.id.commit_mRecyclerview);
        lv_user_comments.setHasFixedSize(true);
        initCommentData();

        mLinearManager = new LinearLayoutManager(getActivity());
        lv_user_comments.setLayoutManager(mLinearManager);
        lv_user_comments.addItemDecoration(new RecycleViewDivider(getActivity(), mLinearManager.HORIZONTAL, 1, Color.rgb(211, 211, 211)));
    }
    private dialog_progress dialog_progress;

    private void setProgress(){
        dialog_progress=new dialog_progress(getActivity());
        dialog_progress.requestWindowFeature(Window.FEATURE_NO_TITLE);

        dialog_progress.setCanceledOnTouchOutside(false);//按返回键可以关闭进度条
        dialog_progress.show();
    }

    private void setRefrsh() {

        lv_user_comments.addOnScrollListener(new RecyclerView.OnScrollListener() {
            private int lastPosition;
            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);

                lastPosition=mLinearManager.findLastVisibleItemPosition();
                if (newState ==RecyclerView.SCROLL_STATE_IDLE && lastPosition + 1 ==commentAdapter.getItemCount()){
                    if (more.equals("1")) {
//                        adapter.changeMoreStatus(ListAdapter.LOADING_MORE);
                        startTime = Calendar.getInstance().getTimeInMillis();
                        if (startTime - endTime > 3000) {
                            page++;
                            TAG_PULL = "MODE";
                            initCommentData();
                            endTime = startTime;
                        }
                    }
                    else {


                    }
                }

            }
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);


            }
        });



    }
    private long startTime,endTime;
    private  int lastpost;//计算adapter最后一个位置
    private Map<Object,Object>map;
    private void initCommentData() {

        setProgress();
        map=new HashMap<Object, Object>();
        map.put("page",page+"");//购买id
        map.put("comment_id",id+"");
        map.put("typed", MyUrl.TYPE);

        setRequest(MyUrl.getcommit,map,handlerCommit,1);
        LogUtils.getInstence().info(MyUrl.getcommit+"?page=1"+"&comment_id="+id+"&typed="+MyUrl.TYPE);




    }
    private void setRequest(String url, Map<Object,Object> map, Handler handler, int tag){

        OkttpUtils.getIntence().OkttpPost(url,map,handler,tag);
    }

    /**
     * 发表评论的监听
     */
    private int typed;//id
    private int page=1;
    private int TAG_SEND=1;
    private int TAG_FLOOR=2;
    private int TAG_MUTAL=3;
    public String comment_id,level="0";
    private View.OnClickListener addCommentListener =(v)-> {
        if (isLogin){
            Bundle bundle=new Bundle();
            bundle.putInt("tag",TAG_SEND);
            bundle.putString("typed",MyUrl.TYPE);
            bundle.putString("level",level);
            bundle.putString("comment_id",id+"");//发表评论获取单行的id
//        JumpIntents.startIntentResultIntent(getActivity(),CommitActivity.class,1,bundle);
            Intent intent=new Intent(getActivity(),CommitActivity.class);
            intent.putExtra("bundle",bundle);
            startActivityForResult(intent,1);
            getActivity().overridePendingTransition(0,0);
        }
        else {JumpLogin();}

    };

    /**
     * 回复评论的监听（回复楼主）
     */
    private View.OnClickListener replyToCommentListener = (v)->{
        if (isLogin){
            int position = (Integer) v.getTag();
            //level 发表评论0   回复是id
            Bundle bundle=new Bundle();
            bundle.putInt("position",position);
            bundle.putInt("tag",TAG_FLOOR);
            bundle.putString("typed",MyUrl.TYPE);
            bundle.putString("level",commentList.get(position).getId()+"");
            bundle.putString("comment_id",comment_id);
            Intent intent=new Intent(getActivity(),CommitActivity.class);
            intent.putExtra("bundle",bundle);
            startActivityForResult(intent,2);
            getActivity().overridePendingTransition(0,0);
        }
        else {
            JumpLogin();
        }
    };

    /**
     * 互相回复的监听（楼中楼）
     */
    private View.OnClickListener replyToReplyListener = (v)->{
        if (isLogin){
            int parentPosition = (Integer) v.getTag(R.id.tag_first);
            int childPosition = (Integer) v.getTag(R.id.tag_second);
//        int position = (Integer) v.getTag();
            //level 发表评论0   回复是id
            Bundle bundle=new Bundle();
            bundle.putInt("parentPosition",parentPosition);
            bundle.putInt("childPosition",childPosition);
            bundle.putInt("tag",TAG_MUTAL);
            bundle.putString("typed",MyUrl.TYPE);
            bundle.putString("level",commentList.get(parentPosition).getCommentses().get(childPosition).getId()+"");
            bundle.putString("comment_id",comment_id);
            Intent intent=new Intent(getActivity(),CommitActivity.class);
            intent.putExtra("bundle",bundle);
            startActivityForResult(intent,3);
            getActivity().overridePendingTransition(0,0);
        }
        else {
            JumpLogin();
        }


    };


    /**
     * 结果回调
     * @param requestCode
     * @param resultCode
     * @param data
     */
    private String content,addtime,thumb,nickname,zan;

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        switch (requestCode){
            case 1:
                if (resultCode==TAG_SEND){//发送评论
                    setResults(1,data);
                }
                break;
            case 2:
                if (resultCode==TAG_FLOOR){//回复楼主
                    setResults(2,data);
                }
                break;
            case 3:
                if (resultCode==TAG_MUTAL){
                    setResults(3,data);
                }
                break;
        }
    }

    private int isid;
    public void setResults(int tag,Intent data){
        page=1;
        commentList.clear();
        if (tag==1){
            TAG_PULL="NORMAR";
            initCommentData();
//
        }
        else if(tag==2){

            TAG_PULL="NORMAR";
            initCommentData();
        }
        else if (tag==3){
            TAG_PULL="NORMAR";

            initCommentData();
        }

    }
    private String TAG_PULL="NORMAR";

    /**
     * 评论
     * @param parentPositon
     * @param childPostion
     */

    private List<comments> replyList;
    private void sendCommit(final int parentPositon,
                            final int childPostion,String content,String addtime,String name,String thumb,String zan){
        switch (childPostion) {
            case ONE_COMMENT_CODE:

                Comment comment = new Comment();
                comment.setContent(content);
                comment.setTime(addtime);
                comment.setZan(zan);
                user_info info=new user_info();
                basic basic= new basic();
                basic.setNickname(name);
                basic.setThumb(thumb);

                info.setBasic(basic);
                comment.setInfo(info);

                commentList.add(comment);
                /**
                 * 插入数据到顶部
                 */
//                commentAdapter.insert(comment,0);
                break;
            default:
                comments comments=new comments();
                comments.setContent(content);
                user_info userInfos=new user_info();
                belong_info infob=new belong_info();

//                if ()
                if (parentPositon != -1) {

//                    comments.setInfo();
//                    reply.setReplyTo(commentList.get(parentPositon)
//                            .getReplyList().get(childPostion)
//                            .getUsername());
//                    commentList.get(parentPositon).getReplyList()
//                            .add(reply);
                } else {//回复楼主
                    basic basicb=new basic();
                    basic basic1=new basic();
                    basic1.setNickname(name);
                    basic1.setContent(content);
                    basic1.setId(isid);
                    basicb.setNickname(name);
                    basicb.setContent(content);
                    basicb.setId(isid);
                    userInfos.setBasic(basic1);
                    infob.setBasic(basicb);
                    comments.setInfo(userInfos);
                    comments.setBelong(infob);
                    replyList=commentList.get(childPostion).getCommentses();
                    replyList.add(comments);

                    commentList.get(childPostion).setCommentses(replyList);
                }
                commentAdapter.clearList();
                commentAdapter.updateList(commentList);
                commentAdapter.notifyDataSetChanged();
                break;
        }
    }
    /**
     * 解析评论数据
     */
    private String jsonString;
    private int code;
    private Handler handlerCommit=new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            try {
                jsonString = msg.getData().getString("result");
                JSONObject object = new JSONObject(jsonString);
                code = object.getInt("code");
                if (code==100){
                    if (msg.what==1){
//                        commentList = new ArrayList<Comment>();
                        if (object.has("result")) {
                            JSONArray result = object.getJSONArray("result");
                            JSONObject extend = object.getJSONObject("extends");
                            more=extend.getString("endfull");
                            for (int i = 0; i < result.length(); i++) {
                                JSONObject data = result.getJSONObject(i);
                                handlerCommitData(data);
                            }
                        }
                        else {
                            JSONObject extend = object.getJSONObject("extends");
                            if (extend.getString("endfull").equals("0")) {
                                ToastUtils.toast("暂无评论");
                                xRefreshView.setLoadComplete(true);
                            }
                        }
                    }
                    else if (msg.what==2){

                        ToastUtils.setToastText(object.getString("msg"),getActivity());

                        JSONObject result = object.getJSONObject("result");
                        int iszan=result.getInt("iszan");
//
                        int zan=result.getInt("zan_count");
                        textView.setText(zan+"");
                    }
                }
                else if (code==403){
                    JSONObject extendss=object.getJSONObject("extends");
                    if (extendss.getString("endfull").equals("0")){
//                        xRefreshView.setLoadComplete(true);
                        ToastUtils.toast("暂无数据");
                    }
                }
                if (TAG_PULL.equals("MODE")){


                }
                else if (TAG_PULL.equals("ZAN")){}
                else {//第一加载数据执行
                    setAdapter();
                }
                if (dialog_progress!=null&&dialog_progress.isShowing()) {

                    dialog_progress.dismiss();
                }

            }
            catch (Exception e){
                e.printStackTrace();
            }
        }
    };

    /**
     * 评论和点赞相同参数地方
     * @param comm
     */
    private void handlerCommitData(JSONObject comm){
        try{
            JSONObject data=comm;
            Comment comment = new Comment();
            comment.setId(data.getInt("id"));
            comment.setUnique(data.getString("unique"));
            comment.setTime(data.getString("addtime"));
            comment.setContent(data.getString("content"));
            level = data.getString("level");

            comment.setLevel(data.getString("level"));
            comment.setTyepd(data.getString("typed"));
            comment.setReplay(data.getString("replay"));
            comment_id = data.getString("comment_id");
            comment.setComment_id(data.getString("comment_id"));
            comment.setZan(data.getString("zan"));
            String commitNumber = data.getString("comment");
            comment.setComment(commitNumber);
            /**
             * userinfo  楼主
             */

            JSONObject user = data.getJSONObject("user_info");
            JSONObject basicin = user.getJSONObject("basic");
            user_info userInfo = new user_info();
            basic basic = new basic();
            userInfo.setState(user.getInt("state"));
            basic.setId(basicin.getInt("id"));
            basic.setUnique(basicin.getString("unique"));
            basic.setThumb(basicin.getString("thumb"));
            basic.setNickname(basicin.getString("nickname"));
            userInfo.setBasic(basic);
            comment.setInfo(userInfo);
            /**
             *评论分层  判断如果comment 等于0没有分成评论
             */
            if (!data.getJSONArray("comments").isNull(0)) {
                List<comments> commentsList = new ArrayList<>();
                JSONArray array = data.getJSONArray("comments");
                for (int j = 0; j < array.length(); j++) {
                    JSONObject datas = array.getJSONObject(j);
                    comments comments = new comments();
                    comments.setId(datas.getInt("id"));
                    comments.setUnique(datas.getString("unique"));
                    comments.setAddtime(datas.getString("addtime"));
                    comments.setContent(datas.getString("content"));
                    comments.setLevel(datas.getString("level"));
                    comments.setTyepd(datas.getString("typed"));
                    comments.setReplay(datas.getString("replay"));

                    JSONObject userd = datas.getJSONObject("user_info");
                    user_info infos = new user_info();
                    JSONObject basicins = userd.getJSONObject("basic");

                    basic basics = new basic();
                    infos.setState(userd.getInt("state"));
                    basics.setId(basicins.getInt("id"));
                    basics.setNickname(basicins.getString("nickname"));
                    basics.setUnique(basicins.getString("unique"));
                    basics.setThumb(basicins.getString("thumb"));
                    infos.setBasic(basics);
                    comments.setInfo(infos);

                    JSONObject belongs = datas.getJSONObject("belong_info");
                    belong_info belongInfo = new belong_info();
                    JSONObject basicinb = belongs.getJSONObject("basic");
                    basic basicb = new basic();
                    belongInfo.setState(belongs.getInt("state"));
                    basicb.setId(basicinb.getInt("id"));
                    basicb.setNickname(basicinb.getString("nickname"));
                    basicb.setUnique(basicinb.getString("unique"));
                    basicb.setThumb(basicinb.getString("thumb"));
                    belongInfo.setBasic(basicb);
                    comments.setBelong(belongInfo);
                    commentsList.add(comments);
                }
                comment.setCommentses(commentsList);
            }
            if (TAG_PULL.equals("MODE")) {
                commentList.add(comment);
                commentAdapter.addData(commentAdapter.getItemCount()-1,comment);

            }
            else if (TAG_PULL.equals("ZAN")){
                commentAdapter.removeData(positionzan);
                commentAdapter.addData(positionzan,comment);

            }
            else {
                commentList.add(comment);
            }
        }
        catch (Exception e){
            e.printStackTrace();
        }
    }
    /**
     * 设置适配器
     */
    private void setAdapter(){
        commentReplyAdapter = null;
        commentAdapter = new Item_Exerciseitem_commitAdapter2(getActivity(),getActivity(), commentList,
                replyToCommentListener, commentReplyAdapter,
                replyToReplyListener,false,1);
        lv_user_comments.setAdapter(commentAdapter);

        /**
         * 点赞
         */
        commentAdapter.setOnClickListener(new OnClickListener() {
            @Override
            public void OnClick(View view, int position) {
                if (isLogin){
                    setProgress();
                    TAG_PULL="ZAN";
                    positionzan=position;
                    textView= (TextView) view.findViewById(R.id.tv_user_praise);

                    Comment comment=commentList.get(positionzan);
                    Map<Object,Object>map=new HashMap<>();
                    LogUtils.getInstence().info("id="+comment.getId()+"");
                    map.put("id",comment.getId()+"");
                    map.put("unique", SharePreceUtils.getOther("user","unique"));
                    map.put("typed","comment");

                    OkttpUtils.getIntence().OkttpPost(MyUrl.ZAN,map,handlerCommit,2);
                }
                else {
                    JumpLogin();
                }
            }
            @Override
            public void OnLongClick(View view, int position) {

            }
        });
        setRefrsh();
    }
    private int positionzan;//赞位置
    private TextView textView;//点赞


    /**
     * 判断是否登录跳转登录界面
     */
    private void JumpLogin(){
        JumpIntents.startIntent(getActivity(),LoginAcitivity.class);

    }

    @Override
    public void onResume() {
        super.onResume();
        isLogin=SharePreceUtils.getBoolean("user","isLogin");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (dialog_progress!=null&&dialog_progress.isShowing()){
            dialog_progress.dismiss();
        }
    }
}
